package cz.semjobKB.treex.service.impl;

import cz.semjobKB.treex.service.api.IRemoteNlp;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

public class RemoteNlp implements IRemoteNlp {

	private final static Logger logger = Logger.getLogger(RemoteNlp.class);
	
	private String TREEX_COMMAND_TEMPLATE = "treex -Lcs Read::Text from=\"input.txt\" W2A::CS::Segment use_paragraphs=0 use_lines=1 W2A::CS::Tokenize W2A::CS::TagMorce W2A::CS::ParseMSTAdapted Write::CoNLLX to=\"output.txt\"";
	
	public synchronized String remoteNlp(String text) {

        logger.info("Received text to processed, invoking treex");
		
		File[] files;
		try {
			files = CreateTemporaryFile(text);
		} catch (IOException e) {
            logger.error("Error creating temp files, \n" + e);
			return null;
		}
		
		String command = TREEX_COMMAND_TEMPLATE;
		command = command.replace("input.txt", files[0].getAbsolutePath());
		command = command.replace("output.txt", files[1].getAbsolutePath());
				
        Process processToolChain;
		try {			
			processToolChain = Runtime.getRuntime().exec(command);
			if (processToolChain.waitFor() != 0) {
                logger.error("Unexpected error during NLP processing!");
            	return null;
            }		
			return FileUtils.readFileToString(files[1]);
		} catch (IOException e) {
            logger.error("Unexpected error during NLP processing!\n" + e.getMessage());
		} catch (InterruptedException e) {
            logger.error("Unexpected error during NLP processing!\n" + e.getMessage());
		}			
		return null;
	}
	
	/**
	 * Creates a temporary file to store the result of NLP
	 */
	private File[] CreateTemporaryFile(String origText) throws IOException {        
		 
		File inputFile = new File(System.getProperty("user.home") + File.separator + "tmp" + File.separator + UUID.randomUUID().toString() + ".txt" );
		FileUtils.writeStringToFile(inputFile, origText);
		
		File outputFile = new File(System.getProperty("user.home") + File.separator + "tmp" + File.separator + UUID.randomUUID().toString() + ".txt" );
    	
        return new File[] {inputFile, outputFile};		
	}

}
